import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { 
  Card, 
  Tabs, 
  Form, 
  Input, 
  Button, 
  Switch, 
  Select, 
  message, 
  Table, 
  Tag,
  Space,
  Modal,
  Avatar,
  Descriptions,
} from 'antd';
import { 
  UserOutlined, 
  SettingOutlined, 
  SafetyCertificateOutlined, 
  BellOutlined,
  CloudUploadOutlined,
  DownloadOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import styles from './SystemSettings.module.css';

const { Option } = Select;
const { TabPane } = Tabs;

// 用户数据类型
interface User {
  id: string;
  username: string;
  email: string;
  role: 'admin' | 'teacher' | 'viewer';
  status: 'active' | 'inactive';
  lastLogin: string;
  createdAt: string;
}

// 系统日志数据类型
interface SystemLog {
  id: string;
  level: 'info' | 'warning' | 'error';
  message: string;
  timestamp: string;
  user: string;
}

const SystemSettings: React.FC = () => {
  const { t } = useTranslation('settings');
  const { t: tCommon } = useTranslation('common');
  const [form] = Form.useForm();
  const [userForm] = Form.useForm();
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);

  // 模拟用户数据
  const [users, setUsers] = useState<User[]>([
    {
      id: '1',
      username: 'admin',
      email: 'admin@school.com',
      role: 'admin',
      status: 'active',
      lastLogin: '2024-01-15 10:30:00',
      createdAt: '2023-01-01'
    },
    {
      id: '2',
      username: 'teacher1',
      email: 'teacher1@school.com',
      role: 'teacher',
      status: 'active',
      lastLogin: '2024-01-14 15:20:00',
      createdAt: '2023-02-01'
    },
    {
      id: '3',
      username: 'viewer1',
      email: 'viewer1@school.com',
      role: 'viewer',
      status: 'inactive',
      lastLogin: '2024-01-10 09:15:00',
      createdAt: '2023-03-01'
    }
  ]);

  // 模拟系统日志
  const [systemLogs, ] = useState<SystemLog[]>([
    {
      id: '1',
      level: 'info',
      message: '系统启动完成',
      timestamp: '2024-01-15 08:00:00',
      user: 'system'
    },
    {
      id: '2',
      level: 'warning',
      message: '数据库连接池接近上限',
      timestamp: '2024-01-15 09:30:00',
      user: 'system'
    },
    {
      id: '3',
      level: 'info',
      message: '用户 admin 登录系统',
      timestamp: '2024-01-15 10:30:00',
      user: 'admin'
    }
  ]);

  // 用户表格列定义
  const userColumns: ColumnsType<User> = [
    {
      title: t('username'),
      dataIndex: 'username',
      key: 'username',
      render: (text) => (
        <Space>
          <Avatar size="small" icon={<UserOutlined />} />
          {text}
        </Space>
      ),
    },
    {
      title: t('email'),
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: t('role'),
      dataIndex: 'role',
      key: 'role',
      render: (role: string) => {
        const color = role === 'admin' ? 'red' : role === 'teacher' ? 'blue' : 'green';
        const text = role === 'admin' ? tCommon('admin') : role === 'teacher' ? tCommon('teacher') : t('viewer');
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: t('status'),
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? t('active') : t('inactive')}
        </Tag>
      ),
    },
    {
      title: t('lastLogin'),
      dataIndex: 'lastLogin',
      key: 'lastLogin',
    },
    {
      title: t('operation'),
      key: 'action',
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEditUser(record)}
          >
            {t('common:edit')}
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteUser(record.id)}
          >
            {t('common:delete')}
          </Button>
        </Space>
      ),
    },
  ];

  // 日志表格列定义
  const logColumns: ColumnsType<SystemLog> = [
    {
      title: t('logLevel'),
      dataIndex: 'level',
      key: 'level',
      render: (level: string) => {
        const color = level === 'error' ? 'red' : level === 'warning' ? 'orange' : 'blue';
        const text = level === 'error' ? t('error') : level === 'warning' ? t('warning') : t('info');
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: t('message'),
      dataIndex: 'message',
      key: 'message',
    },
    {
      title: t('user'),
      dataIndex: 'user',
      key: 'user',
    },
    {
      title: t('timestamp'),
      dataIndex: 'timestamp',
      key: 'timestamp',
    },
  ];

  // 处理系统配置保存
  const handleSystemConfigSave = (values: any) => {
    console.log('系统配置:', values);
    message.success(t('configSaved'));
  };

  // 处理通知设置保存
  const handleNotificationSave = (values: any) => {
    console.log('通知设置:', values);
    message.success(t('notificationSaved'));
  };

  // 处理添加用户
  const handleAddUser = () => {
    setEditingUser(null);
    userForm.resetFields();
    setUserModalVisible(true);
  };

  // 处理编辑用户
  const handleEditUser = (user: User) => {
    setEditingUser(user);
    userForm.setFieldsValue(user);
    setUserModalVisible(true);
  };

  // 处理删除用户
  const handleDeleteUser = (id: string) => {
    Modal.confirm({
      title: t('confirmDelete'),
      content: t('confirmDeleteUser'),
      onOk: () => {
        setUsers(users.filter(user => user.id !== id));
        message.success(t('deleteSuccess'));
      },
    });
  };

  // 处理用户表单提交
  const handleUserSubmit = (values: any) => {
    if (editingUser) {
      // 更新用户
      setUsers(users.map(user => 
        user.id === editingUser.id ? { ...user, ...values } : user
      ));
      message.success('用户信息更新成功');
    } else {
      // 添加新用户
      const newUser: User = {
        id: Date.now().toString(),
        ...values,
        lastLogin: '从未登录',
        createdAt: new Date().toISOString().split('T')[0]
      };
      setUsers([...users, newUser]);
      message.success(t('addSuccess'));
    }
    setUserModalVisible(false);
  };

  // 处理数据备份
  const handleBackup = () => {
    message.success('数据备份任务已开始，请稍后查看下载');
  };

  // 处理数据恢复
  const handleRestore = () => {
    message.info('数据恢复功能开发中');
  };

  return (
    <div className={styles.systemSettings}>
      <Card title={t('title')} bordered={false} className={styles.card}>
        <Tabs defaultActiveKey="system" type="card" className={styles.tabsCard}>
          {/* 系统配置标签页 */}
          <TabPane 
            tab={
              <span>
                <SettingOutlined />
                {t('systemConfig')}
              </span>
            } 
            key="system"
          >
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSystemConfigSave}
              initialValues={{
                schoolName: 'XX大学',
                academicYear: '2023-2024',
                semester: '第二学期',
                dataRetention: '365'
              }}
            >
              <Card title={t('basicConfig')} style={{ marginBottom: 16 }} className={styles.card}>
                <Form.Item label={t('schoolName')} name="schoolName" className={styles.formItem}>
                  <Input placeholder={t('pleaseInput') + t('schoolName')} />
                </Form.Item>
                
                <Form.Item label={t('academicYear')} name="academicYear" className={styles.formItem}>
                  <Input placeholder={t('pleaseInput') + t('academicYear')} />
                </Form.Item>
                
                <Form.Item label={t('semester')} name="semester" className={styles.formItem}>
                  <Select>
                    <Option value="第一学期">{t('firstSemester')}</Option>
                    <Option value="第二学期">{t('secondSemester')}</Option>
                    <Option value="暑期学期">{t('summerSemester')}</Option>
                  </Select>
                </Form.Item>
                
                <Form.Item label={t('dataRetention')} name="dataRetention" className={styles.formItem}>
                  <Input type="number" placeholder={t('pleaseInput') + t('dataRetention')} />
                </Form.Item>
              </Card>

              <Card title={t('functionSwitches')} style={{ marginBottom: 16 }} className={styles.card}>
                <Form.Item label="允许学生自助注册" name="studentSelfRegister" valuePropName="checked" className={styles.formItem}>
                  <Switch />
                </Form.Item>
                
                <Form.Item label="启用成绩预警" name="gradeWarning" valuePropName="checked" className={styles.formItem}>
                  <Switch />
                </Form.Item>
                
                <Form.Item label="启用考勤自动统计" name="attendanceAutoCount" valuePropName="checked" className={styles.formItem}>
                  <Switch />
                </Form.Item>
              </Card>

              <Form.Item className={styles.formItem}>
                <Button type="primary" htmlType="submit">
                  {t('saveConfig')}
                </Button>
              </Form.Item>
            </Form>
          </TabPane>

          {/* 用户管理标签页 */}
          <TabPane 
            tab={
              <span>
                <UserOutlined />
                {t('userManagement')}
              </span>
            } 
            key="users"
          >
            <div className={styles.userManagement}>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleAddUser}>
                {t('addUser')}
              </Button>
            </div>
            
            <Table 
              columns={userColumns} 
              dataSource={users} 
              rowKey="id"
              pagination={false}
            />
          </TabPane>

          {/* 通知设置标签页 */}
          <TabPane 
            tab={
              <span>
                <BellOutlined />
                通知设置
              </span>
            } 
            key="notifications"
          >
            <Form
              layout="vertical"
              onFinish={handleNotificationSave}
              initialValues={{
                emailNotifications: true,
                smsNotifications: false,
                newStudentAlert: true,
                gradeUpdateAlert: true,
                systemMaintenanceAlert: true
              }}
            >
              <Card title="通知渠道" style={{ marginBottom: 16 }} className={styles.card}>
                <Form.Item label="邮件通知" name="emailNotifications" valuePropName="checked" className={styles.formItem}>
                  <Switch />
                </Form.Item>
                
                <Form.Item label="短信通知" name="smsNotifications" valuePropName="checked" className={styles.formItem}>
                  <Switch />
                </Form.Item>
              </Card>

              <Card title="通知类型" style={{ marginBottom: 16 }} className={styles.card}>
                <Form.Item label="新学生注册提醒" name="newStudentAlert" valuePropName="checked" className={styles.formItem}>
                  <Switch />
                </Form.Item>
                
                <Form.Item label="成绩更新提醒" name="gradeUpdateAlert" valuePropName="checked" className={styles.formItem}>
                  <Switch />
                </Form.Item>
                
                <Form.Item label="系统维护提醒" name="systemMaintenanceAlert" valuePropName="checked" className={styles.formItem}>
                  <Switch />
                </Form.Item>
              </Card>

              <Form.Item className={styles.formItem}>
                <Button type="primary" htmlType="submit">
                  保存通知设置
                </Button>
              </Form.Item>
            </Form>
          </TabPane>

          {/* 安全设置标签页 */}
          <TabPane 
            tab={
              <span>
                <SafetyCertificateOutlined />
                安全设置
              </span>
            } 
            key="security"
          >
            <Card title="密码策略" style={{ marginBottom: 16 }} className={styles.card}>
              <Descriptions column={1} bordered>
                <Descriptions.Item label="密码最小长度">8位</Descriptions.Item>
                <Descriptions.Item label="密码复杂度要求">必须包含字母和数字</Descriptions.Item>
                <Descriptions.Item label="密码过期时间">90天</Descriptions.Item>
                <Descriptions.Item label="最大登录尝试次数">5次</Descriptions.Item>
              </Descriptions>
            </Card>

            <Card title="会话管理" className={styles.card}>
              <Form layout="vertical">
                <Form.Item label="会话超时时间" className={styles.formItem}>
                  <Select defaultValue="30">
                    <Option value="15">15分钟</Option>
                    <Option value="30">30分钟</Option>
                    <Option value="60">60分钟</Option>
                    <Option value="120">2小时</Option>
                  </Select>
                </Form.Item>
                
                <Form.Item className={styles.formItem}>
                  <Button type="primary">更新安全设置</Button>
                </Form.Item>
              </Form>
            </Card>
          </TabPane>

          {/* 数据管理标签页 */}
          <TabPane 
            tab={
              <span>
                <CloudUploadOutlined />
                数据管理
              </span>
            } 
            key="data"
          >
            <Card title="数据备份" style={{ marginBottom: 16 }} className={styles.card}>
              <p>备份系统数据到本地文件</p>
              <Button 
                type="primary" 
                icon={<DownloadOutlined />} 
                onClick={handleBackup}
                style={{ marginRight: 16 }}
              >
                立即备份
              </Button>
              <Button icon={<CloudUploadOutlined />} onClick={handleRestore}>
                数据恢复
              </Button>
            </Card>

            <Card title="数据统计" className={styles.card}>
              <Descriptions column={2} bordered>
                <Descriptions.Item label="学生总数">1,254人</Descriptions.Item>
                <Descriptions.Item label="教师总数">89人</Descriptions.Item>
                <Descriptions.Item label="课程总数">156门</Descriptions.Item>
                <Descriptions.Item label="系统使用时间">365天</Descriptions.Item>
              </Descriptions>
            </Card>
          </TabPane>

          {/* 系统日志标签页 */}
          <TabPane 
            tab={
              <span>
                <SafetyCertificateOutlined />
                {t('systemLogs')}
              </span>
            } 
            key="logs"
          >
            <Table 
              columns={logColumns} 
              dataSource={systemLogs} 
              rowKey="id"
              pagination={{ pageSize: 10 }}
              size="small"
            />
          </TabPane>
        </Tabs>
      </Card>

      {/* 用户管理模态框 */}
      <Modal
        title={editingUser ? t('editUser') : t('addUser')}
        open={userModalVisible}
        onCancel={() => setUserModalVisible(false)}
        footer={null}
        width={500}
      >
        <Form
          form={userForm}
          layout="vertical"
          onFinish={handleUserSubmit}
        >
          <Form.Item
            label={t('username')}
            name="username"
            rules={[{ required: true, message: t('pleaseInput') + t('username') }]}
            className={styles.formItem}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label={t('email')}
            name="email"
            rules={[
              { required: true, message: t('pleaseInput') + t('email') },
              { type: 'email', message: t('pleaseInput') + t('email') }
            ]}
            className={styles.formItem}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label={t('role')}
            name="role"
            rules={[{ required: true, message: t('pleaseSelect') + t('role') }]}
            className={styles.formItem}
          >
            <Select>
              <Option value="admin">{t('admin')}</Option>
              <Option value="teacher">{t('teacher')}</Option>
              <Option value="viewer">{t('viewer')}</Option>
            </Select>
          </Form.Item>

          <Form.Item
            label={t('status')}
            name="status"
            rules={[{ required: true, message: t('pleaseSelect') + t('status') }]}
            className={styles.formItem}
          >
            <Select>
              <Option value="active">{t('active')}</Option>
              <Option value="inactive">{t('inactive')}</Option>
            </Select>
          </Form.Item>

          {!editingUser && (
            <Form.Item
              label={t('initialPassword')}
              name="password"
              rules={[{ required: true, message: t('pleaseInput') + t('initialPassword') }]}
              className={styles.formItem}
            >
              <Input.Password />
            </Form.Item>
          )}

          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => setUserModalVisible(false)}>
                {t('common:cancel')}
              </Button>
              <Button type="primary" htmlType="submit">
                {editingUser ? t('common:update') : t('addUser')}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default SystemSettings;